package com.common.core.utils;

import java.util.Map;

import com.common.core.constants.JwtConstants;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;


public class JwtUtils {
    // 生成令牌
    public static String createToken(Map<String, Object> claims, String secret) {
        String token = Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512, secret).compact();
        return token;
    }
    // 从令牌中获取数据
    public static Claims parseToken(String token, String secret) {
        if (token == null || secret == null) {
            throw new IllegalArgumentException("Token或Secret不能为空");
        }
        
        // 验证token格式
        if (!token.contains(".")) {
            throw new IllegalArgumentException("Token格式无效");
        }
        
        // 移除Bearer前缀（如果存在）
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        
        return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
    }

    public static String getUserKey(Claims claims) {
        return toStr(claims.get(JwtConstants.LOGIN_USER_KEY));
    }

    public static String getUserId(Claims claims) {
        return toStr(claims.get(JwtConstants.LOGIN_USER_ID));
    }

    private static String toStr(Object value) {
        if(value == null) return null;
        return value.toString();
    }

    //secret: shuienokagufdasebguersewpiqng
}
